#购物车数据合并
import base64
import pickle

from django_redis import get_redis_connection


def merge_cookie_redis_data(request, response):
    """

    :param request: 获取cookie数据， 获取redis数据使用的
    :param response:
    :return:
    """

    cookie_cart = request.COOKIES.get("carts")
    if cookie_cart:  # 如果之前操作购物车则有数据
        # encode 得到的是6位的byte类型
        cookie_cart_cart = pickle.loads(base64.b64decode(cookie_cart.encode()))
    else:
        return response

    redis_conn = get_redis_connection('carts')
    for sku_id, selected_count in cookie_cart_cart.items():
        # cookie购物车数据覆盖redis购物车数据
        redis_conn.hset("carts_%s" % request.user.id, sku_id, selected_count['count'])
        selected = selected_count['selected']
        # cookie购物车数据覆盖redis购物车数据
        if selected:
            redis_conn.sadd("selected_%s" % request.user.id, sku_id)
        else:
            redis_conn.srem("selected_%s" % request.user.id, sku_id)
    response.delete_cookie('carts')
    return response